import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/phoenix/api/revision_main_api.dart';
import 'package:dk_flutter_module_sale/phoenix/message/second_message/bean/bean_second__message.dart';
import 'package:dk_flutter_module_sale/phoenix/message/second_message/widget/widget_right_item_title.dart';
import 'package:dk_flutter_module_sale/phoenix/message/second_message/widget/widget_second_message.dart';

//路由注解
@ARoute(url: CommonWidgetRoute.SECOND_MESSAGE_LIST)
class SubMessagePage extends CommonPage {
  final WidgetOption option;
  SubMessagePage(this.option) : super();
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    ParamBean configBean = ParamBean.fromJson(this.option.widgetParams);
    print(this.option.widgetParams);
    Map<String, dynamic> queryMap = Map<String, dynamic>();
    queryMap["type"] = configBean.type;
    queryMap["pageSize"] = 20;
    queryMap["pageIndex"] = 1;
    pageBloc.pageHttpGet(
        path: RevisionMainApi.secondMessageUrl,
        queryMap: queryMap,
        widgetBuilderByData: (dynamic data) {
          DataBean dataBean = DataBean.fromJson(data);
          return MessageWidget(pageBloc, dataBean, configBean);
        });
  }
}

class MessageWidget extends StatefulWidget {
  final ParamBean configBean;
  final CommonPageBloc pageBloc;
  final DataBean dataBean;
  MessageWidget(this.pageBloc, this.dataBean, this.configBean);
  @override
  MessageState createState() {
    return MessageState(this.pageBloc, this.dataBean, this.configBean);
  }
}

class MessageState extends State<MessageWidget>
    with SingleTickerProviderStateMixin {
  final ParamBean configBean;
  CommonPageBloc messageBloc;
  DataBean dataBean;
  DkEasyRefreshController easyRefreshController;
  int pageIndex = 1;
  RefreshRightItemTitleBloc refreshRightItemTitleBloc;
  MessageState(this.messageBloc, this.dataBean, this.configBean);

  @override
  void initState() {
    super.initState();
    easyRefreshController = DkEasyRefreshController();
    refreshRightItemTitleBloc =
        RefreshRightItemTitleBloc(unreadCount: this.dataBean.unreadCount);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: Container(
        color: Color(0xFFF5F5F5),
        child: this.buildListWidget(context),
      ),
    );
  }

  Future<void> refreshPage() async {
    Map<String, dynamic> map = Map<String, dynamic>();
    this.pageIndex = 1;
    map['pageIndex'] = this.pageIndex;
    map["pageSize"] = 20;
    map["type"] = this.configBean.type;
    widget.pageBloc.dataHttpGet(
        path: RevisionMainApi.secondMessageUrl,
        queryMap: map,
        handleResult: (dynamic data) {
          setState(() {
            this.dataBean = DataBean.fromJson(data);
            easyRefreshController.finishRefresh(success: true);
            this
                .refreshRightItemTitleBloc
                .dispatch("${this.dataBean.unreadCount}");
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishRefresh(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishRefresh(success: false);
        });
  }

  Future<void> loadMore() async {
    Map<String, dynamic> map = Map<String, dynamic>();
    map['pageIndex'] = (++this.pageIndex);
    map["pageSize"] = 20;
    map["type"] = this.configBean.type;
    widget.pageBloc.dataHttpGet(
        path: RevisionMainApi.secondMessageUrl,
        queryMap: map,
        handleResult: (dynamic data) {
          setState(() {
            DataBean addDataBean = DataBean.fromJson(data);
            this.dataBean.rows.addAll(addDataBean.rows);
            easyRefreshController.finishLoad(
                success: true,
                noMore: this.pageIndex >= this.dataBean.totalPage);
            this
                .refreshRightItemTitleBloc
                .dispatch("${this.dataBean.unreadCount}");
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }

  Widget buildListWidget(BuildContext context) {
    bool noMore = this.pageIndex >= this.dataBean.totalPage;
    return Container(
      color: Colors.white,
      child: DkRefreshListWidget.custom(
          controller: easyRefreshController,
          onLoad: noMore ? null : this.loadMore,
          onRefresh: this.refreshPage,
          emptyWidget: this.dataBean.rows.length == 0
              ? LogicPage(PortalConfig.smallEmptyPageParam)
              : null,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  MessageList bean = dataBean.rows[index];
                  return Container(
                    height: 90,
                    child: SecondMessageWidget(
                      messageListBean: bean,
                      tapCallback: () {
                        //已读消息
                        if (bean.hasRead == 0) {
                          this.messageBloc.dataHttpPost(
                              path: RevisionMainApi.readMessageUrl +
                                  "/${bean.id}",
                              handleResult: (dynamic data) {
                                setState(() {
                                  bean.hasRead = 1;
                                  this.refreshRightItemTitleBloc.dispatch(
                                      "${--this.dataBean.unreadCount}");
                                });
                              });
                        }
                        RouteUtil.goPage(bean.appRouteUrl);
                      },
                    ),
                  );
                },
                childCount: this.dataBean.rows.length,
              ),
            ),
          ]),
    );
  }

  Widget buildAppBar(BuildContext context) {
    return DkAppBar(DKAppBarParams.withBackMenu(
        context,
        [
          Container(
            height: 30,
            child: Container(
              height: 10,
              //width: 100,
              //color: Colors.orange,
              child: Align(
                alignment: Alignment.centerRight,
                child: buildRightNavigationItem(),
              ),
            ),
          ),
        ],
        title: Text(this.configBean.title)));
  }

  Widget buildRightNavigationItem() {
    if (this.dataBean.unreadCount == 0) {
      return Text("");
    } else if (this.dataBean.unreadCount > 0 &&
        this.dataBean.unreadCount < 10) {
      return buildOneMessage();
    } else {
      String countStr = "";
      if (this.dataBean.unreadCount > 99) {
        countStr = "  99+  ";
      } else {
        countStr = "  ${this.dataBean.unreadCount}  ";
      }
      return buildMore9Message(countStr);
    }
  }

  Widget buildMore9Message(String countStr) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(right: 10),
      height: 16,
      decoration: BoxDecoration(
          color: Color(0xFFFF5D6A), borderRadius: BorderRadius.circular(8)),
      child: Text(
        countStr,
        style: TextStyle(
          color: Colors.white,
          fontSize: 11,
        ),
        //textAlign: TextAlign.center,
      ),
    );
  }

  Widget buildOneMessage() {
    return Container(
      alignment: Alignment.center,
      width: 16,
      height: 16,
      margin: EdgeInsets.only(right: 10),
      child: BlocProvider<RefreshRightItemTitleBloc>(
          builder: (BuildContext context) {
            return this.refreshRightItemTitleBloc;
          },
          child: RightItemTitle(
            title: "${this.dataBean.unreadCount}",
          )),
      decoration: BoxDecoration(
          color: Color(0xFFFF5D6A), borderRadius: BorderRadius.circular(8)),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
